import time
import re
from config import Config
import requests
from logger import logging
from browser_utils import BrowserManager
import random

class EmailVerificationHandler:
    def __init__(self):
        self.username = Config().get_temp_mail()
        self.session = requests.Session()
        self.emailExtension = "@mailto.plus"

    def get_verification_code(self):
        code = None

        try:
            print("正在处理...")

            # 等待并获取最新邮件
            code, first_id = self._get_latest_mail_code()

            # 清理邮件
            self._cleanup_mail(first_id)

        except Exception as e:
            print(f"获取验证码失败: {str(e)}")

        return code

    # 手动输入验证码
    def _get_latest_mail_code(self):
        # 获取邮件列表
        mail_list_url = f"https://tempmail.plus/api/mails?email={self.username}{self.emailExtension}&limit=20&epin="
        mail_list_response = self.session.get(mail_list_url)
        mail_list_data = mail_list_response.json()
        time.sleep(0.5)
        if not mail_list_data.get("result"):
            return None, None

        # 获取最新邮件的ID
        first_id = mail_list_data.get("first_id")
        if not first_id:
            return None, None

        # 获取具体邮件内容
        mail_detail_url = f"https://tempmail.plus/api/mails/{first_id}?email={self.username}{self.emailExtension}&epin="
        mail_detail_response = self.session.get(mail_detail_url)
        mail_detail_data = mail_detail_response.json()
        time.sleep(0.5)
        if not mail_detail_data.get("result"):
            return None, None

        # 从邮件文本中提取6位数字验证码
        mail_text = mail_detail_data.get("text", "")
        code_match = re.search(r"\b\d{6}\b", mail_text)

        if code_match:
            return code_match.group(), first_id
        return None, None

    def _cleanup_mail(self, first_id):
        # 构造删除请求的URL和数据
        delete_url = "https://tempmail.plus/api/mails/"
        payload = {
            "email": f"{self.username}{self.emailExtension}",
            "first_id": first_id,
            "epin": "",
        }

        # 最多尝试5次
        for _ in range(5):
            response = self.session.delete(delete_url, data=payload)
            try:
                result = response.json().get("result")
                if result is True:
                    return True
            except:
                pass

            # 如果失败,等待0.5秒后重试
            time.sleep(0.5)

        return False


if __name__ == "__main__":
    # email_handler = EmailVerificationHandler()
    # code = email_handler.get_verification_code()
    # print(code)
    
    logging.info("正在初始化浏览器...")
    browser_manager = BrowserManager()
    browser = browser_manager.init_browser()
    webmailTab = browser.new_tab()
    webmailTab.get("https://mail.cjoop.top/webmail/")
    
    if webmailTab.ele("@id=rcmloginuser"):
        webmailTab.actions.click("@id=rcmloginuser").input("qvpdkkfr672652@cjoop.top")
        webmailTab.actions.click("@id=rcmloginpwd").input("vfpd5@npA^Wa")
        webmailTab.actions.click("@type=submit")
        logging.info("成功登录新邮箱")
        time.sleep(random.uniform(1, 3))
        verify_link = webmailTab.ele('tag:a@@text():Verify your email address')
        if verify_link:
            logging.info("找到 Verify your email address 链接")
            href = verify_link.attr('href')
            logging.info(f"链接的 href 属性: {href}")
            verify_link.click()
            time.sleep(random.uniform(1, 3))
            iframe = webmailTab.get_frame('@id:messagecontframe')
            messageBody = iframe.ele('@id=messagebody')
            mail_text = messageBody.text
            code_match = re.search(r"\b\d{6}\b", mail_text)
            if code_match:
                logging.info(code_match.group())
        logging.info("...")
    else:
        logging.error("未找到 Verify your email address 链接")
    
